package com.xh.shiro;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/*
 * @author：Zero度
 * @2020/12/11 12:20
 * 文件说明：
 * */
@Configuration
public class ShiroConfig {

    /**
     * 安全管理器
     * @param defaultWebSecurityManager
     * @return
     */
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();

        // 设置安全管理器
        bean.setSecurityManager(defaultWebSecurityManager);

        // 添加shiro的内置过滤器
        /**
         * anon: 无序认证就可以访问
         * authc: 必须认证才能访问
         * user: 必须拥有记住我功能才可用
         * perms: 拥有对某个资源的权限才能访问
         * role: 拥有某个角色权限才能访问
         */
        return bean;
    }

    /**
     * 管理用户
     * @param authRealm
     * @return
     */
    @Bean(name="securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("authRealm") LoginRealm authRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联LoginRealm
        securityManager.setRealm(authRealm);
        return securityManager;
    }

    /**
     * 创建realm对象,登录验证
     * @return
     */
    @Bean
    public LoginRealm authRealm(){
        LoginRealm loginRealm = new LoginRealm();
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        // 设置加密算法
        credentialsMatcher.setHashAlgorithmName("MD5");
        // 设置Hash次数
        credentialsMatcher.setHashIterations(1024);
        // 设置凭证匹配器
//        loginRealm.setCredentialsMatcher(credentialsMatcher);
        credentialsMatcher.setStoredCredentialsHexEncoded(true);
        loginRealm.setCredentialsMatcher(credentialsMatcher);
        return loginRealm;
    }
}